import Vue from "vue";
import VueRouter from 'vue-router';
Vue.use(VueRouter);
import store from "@/store";

let originPush = VueRouter.prototype.push;
let originReplace = VueRouter.prototype.replace;

VueRouter.prototype.push = function (location, reslove, reject) {
    (reslove && reject) ? originPush.call(this, location, reslove, reject): originPush.call(this, location, () => {}, () => {});
}
VueRouter.prototype.replace = function (location, reslove, reject) {
    (reslove && reject) ? originReplace.call(this, location, reslove, reject): originReplace.call(this, location, () => {}, () => {});
}

import routes from './routes';

const router = new VueRouter({
    routes,
    scrollBehavior(to, from, savedPosition) {
        return {
            x: 0,
            y: 0
        }
    }
});

//配置前置守卫
router.beforeEach(async (to, from, next) => {
    let token = store.getters.token;
    let name = store.getters.userInfo.name;
    //判断是否已登录
    if (token) {
        //登录后不能在访问登录页
        if (to.path == '/login') {
            //定向到home页
            next('/home');
        } else {
            //判断是否有用户信息
            if (name) {
                next();
            } else {
                try {
                    //没有用户信息则发请求
                    await store.dispatch('getUserInfo');
                    next();
                } catch (error) {
                    //用户退出或者token失效
                    await store.dispatch('loginOut');
                    next('/login');
                }
            }
        }
    } else {
        let toPath = to.path;
        //访问trade、支付、支付成功、个人中心【我的订单、团购订单】,跳转到登录页
        if (toPath.indexOf('trade') != -1 || toPath.indexOf('pay') != -1 || toPath.indexOf('center') != -1) {
            alert('请先登录');
            next(`/login?redirect=${toPath}`);
        } else next();
    }
})

export default router;